package main

import (
	"context"
	"dash/topics"
	"database/sql"
	"io/ioutil"
	"os"
	"os/signal"
	"syscall"

	"github.com/go-kit/kit/log"
	"github.com/go-redis/redis/v8"
	"gopkg.in/yaml.v3"
)

var cfg config

func init() {
	configBytes, err := ioutil.ReadFile("config.yaml")
	if err != nil {
		panic(err)
	}
	err = yaml.Unmarshal(configBytes, &cfg)
	if err != nil {
		panic(err)
	}
}

func main() {
	rClient := redis.NewClient(&redis.Options{
		Network: "tcp",
		Addr:    cfg.RedisDSN,
		DB:      cfg.RedisDB,
	})
	sqlClient, err := sql.Open("mysql", cfg.MysqlDSN)
	if err != nil {
		panic(err)
	}

	logger := log.NewJSONLogger(os.Stdout)
	logger = log.With(logger, "ts", log.DefaultTimestamp)
	logger = log.With(logger, "caller", log.DefaultCaller)

	ctx := context.Background()
	nService := topics.NewNumberService("topic_version", rClient)
	topicRepo := topics.NewRepository(sqlClient, logger)

	upgradeRepository := topics.NewUpgradeRepository(rClient)
	var upgradeService topics.UpgradeService
	upgradeService = topics.NewUpgradeService(ctx, topicRepo, nService, upgradeRepository, logger, cfg.TopicVersionKey)

	done := make(chan struct{})
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

	go upgradeService.Loop(ctx, done, sigs)
	<-done
}
